from flask import Flask
from flask import jsonify,render_template
from flask import request
from flask_cors import CORS
from models import todo,get_uid
from datetime import datetime

app = Flask(__name__)

#解决跨域问题
CORS(app,supports_credentials=True)

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/todo',methods=['GET', 'POST'])
def todo_view():
    if request.method == 'GET':
        return jsonify(todo.todo_list)
    if request.method == 'POST':
        title = request.json.get('title',None)
        item = {
            'id':get_uid(),
            'title':title,
            'done':False,
            'creat_time':datetime.now().strftime("%Y%m%d")
        }
        todo.todo_list.insert(0,item)
        return {'status':'ok'}
    

@app.route('/todo/<_id>',methods=['PUT', 'DELETE'])
def todo_item(_id):
    if request.method == 'PUT':
        for item in todo.todo_list:
            if  item['id'] == _id:
                item['done']= not item['done']
                return {'status':'ok'}
        return {'status':'error'}
    if request.method == 'DELETE':
        for item in todo.todo_list:
            if item['id']== _id:
                todo.todo_list.remove(item)
                return {'status':'ok'}
        return {'status':'error'}
    

if __name__ == '__main__':
    app.run(debug=True)